<?php
namespace App\Admin\Controllers;
use App\Admin\Models\OrderCommissions;
use App\Admin\Models\Orders;
use App\Admin\Models\User;
use Common\Common;
use Common\ControllerAdBase;
use Phalcon\Paginator\Adapter\Model as PaginatorModel;
class DatareportController extends ControllerAdBase
{

    public function initialize()
    {
        parent::initialize();
    }

    /**
     * 订单明细
     */
    public function orderListAction()
    {
        $order = new Orders();
        $list  = $order->get_list($this->params);
        foreach ($list['list'] as $key => $value) {
            if ($value['pay_money'] == 0 || $value['commition'] == 0) {
                $income_rate = 0;
            } else {
                $income_rate = ($value['reality_commition'] / $value['pay_money']) * 100;
            }
            $list['list'][$key]['income_rate'] = (isset($value['commition']) && $value['commition'] > 0) ? Common::number_randtwo($income_rate) : '0.00';
        }
        $list['estimate_commition'] = isset($list['estimate_commition']) ? Common::number_randtwo($list['estimate_commition']) : '0.00';
        $list['estimate_profit']    = isset($list['estimate_profit']) ? Common::number_randtwo($list['estimate_profit']) : '0.00';
        $this->ok($list);
    }

    public function commitionDetailsAction()
    {
        if (!isset($this->params['order_id']) || empty($this->params['order_id'])) {
            $this->fail(-1, '缺少订单ID');
        }
        $list                = new OrderCommissions();
        $where['conditions'] = "order_id = '{$this->params['order_id']}'";
        $list                = $list->find($where)->toarray();
        if (!empty($list)) {
            $user = new User();
            foreach ($list as $key => $val) {
                $userInfo                = $user->findFirstById($val['user_id']);
                $list[$key]['nickname']  = '用户未找到!';
                $list[$key]['type_name'] = '分佣';
                if ($val['buyer_id'] == $val['user_id']) {
                    $list[$key]['type_name'] = '自购';
                }
                if ($userInfo) {
                    $list[$key]['nickname'] = $userInfo->nickname;
                }
            }
        }
        $this->ok($list);
    }

    /**
     * 预估利润统计
     */
    public function orderCommitionSumAction()
    {
        $order                        = new Orders();
        $result['estimate_commition'] = $order->order_sum();
        $order                        = new OrderCommissions();
        $estimate_profit              = $order->commissionSum();
        $result['estimate_profit']    = Common::number_randtwo($result['estimate_commition'] - $estimate_profit);

        $this->ok($result);
    }

    /**
     * 订单排行
     */
    public function orderTopAction()
    {
        $order = new Orders();
        $list  = $order->orderTop($this->params);
        $this->ok($list);
    }

    public function userTopAction()
    {
        $user = new OrderCommissions();
        $list = $user->userTop($this->params);
        $this->ok($list);
    }


    /**
     * 结算列表
     */
    public function tallyorderAction()
    {
        if (!isset($this->params['page']) && empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        if (!isset($this->params['limit']) && empty($this->params['limit'])) {
            $this->params['limit'] = 10;
        }
        if (!isset($this->params['data']) && empty($this->params['data'])) {
            $time                    = Common::timeChange(9);
            $this->params['data'][0] = $time['start_at'];
            $this->params['data'][1] = $time['end_at'];
        } else {
            $date = $this->params['data'];
            unset($this->params['data']);
            $this->params['data'][0] = $date . '-01 00:00:00';
            $this->params['data'][1] = date('Y-m-01 00:00:00', strtotime($date) + 32 * 86400);
        }

        $orderCommissionDb = new OrderCommissions();
        $result['item']    = $orderCommissionDb->getsettlement($this->params);
        $result['total']   = $orderCommissionDb->getsettlement($this->params, 'count');
        if (!empty($result['item'])) {
            $result['user_ids'] = implode(',', array_column($result['item'], 'user_id'));
        } else {
            $result['user_ids'] = '';
        }
        $this->ok($result);
    }

    public function detareport_detailAction()
    {
        if (!isset($this->params['page']) && empty($this->params['page'])) {
            $this->params['page'] = 1;
        }
        if (!isset($this->params['user_id']) && empty($this->params['user_id'])) {
            $this->fail(-1, '缺少user_id');
        }
        if (!isset($this->params['limit']) && empty($this->params['limit'])) {
            $this->params['limit'] = 10;
        }
        if (!isset($this->params['data']) && empty($this->params['data'])) {
            $time                    = Common::timeChange(9);
            $this->params['data'][0] = $time['start_at'];
            $this->params['data'][1] = $time['end_at'];
        } else {
            $date = $this->params['data'];
            unset($this->params['data']);
            $this->params['data'][0] = $date . '-01 00:00:00';
            $this->params['data'][1] = date('Y-m-01 00:00:00', strtotime($date) + 32 * 86400);
        }
        $orderCommissionDb = new OrderCommissions();

        $list = $orderCommissionDb->detareport_detail($this->params);
        $this->ok($list);
    }

    /**
     * 结算统计
     */
    public function orderCountsAction()
    {
        if (!isset($this->params['data']) && empty($this->params['data'])) {
            $time                    = Common::timeChange(9);
            $this->params['data'][0] = $time['start_at'];
            $this->params['data'][1] = $time['end_at'];
        } else {
            $date = $this->params['data'];
            unset($this->params['data']);
            $this->params['data'][0] = $date . '-01 00:00:00';
            $this->params['data'][1] = date('Y-m-01 00:00:00', strtotime($date) + 32 * 86400);
        }
        $orderCommissionDb = new OrderCommissions();
        $result            = $orderCommissionDb->order_count($this->params);
        $list['taobao']    = 0;
        $list['jd']        = 0;
        $list['pdd']       = 0;
        $list['suning']    = 0;
        $list['vph']       = 0;
        $list['qita']      = 0;
        if (!empty($result)) {
            foreach ($result as $val) {
                switch ($val['order_channel']) {
                    case 'haodanku':
                        $list['taobao'] += $val['money'];
                        $list['taobao'] = Common::number_randtwo($list['taobao']);
                        break;
                    case 'elm':
                        $list['taobao'] += $val['money'];
                        $list['taobao'] = Common::number_randtwo($list['taobao']);
                        break;
                    case 'jd':
                        $list['jd'] = $val['money'];
                        $list['jd'] = Common::number_randtwo($list['jd']);
                        break;
                    case 'pdd':
                        $list['pdd'] = $val['money'];
                        $list['pdd'] = Common::number_randtwo($list['pdd']);
                        break;
                    case 'suning':
                        $list['suning'] = $val['money'];
                        $list['suning'] = Common::number_randtwo($list['suning']);
                        break;
                    case 'vph':
                        $list['vph'] = $val['money'];
                        $list['vph'] = Common::number_randtwo($list['vph']);
                        break;
                    default:
                        $list['qita'] += $val['money'];
                        $list['qita'] = Common::number_randtwo($list['qita']);
                }
            }
        }
        $list['total'] = $list['taobao'] + $list['jd'] + $list['pdd'] + $list['suning'] + $list['vph'] + $list['qita'];

        $list['settlement_taobao'] = 0;
        $list['settlement_jd']     = 0;
        $list['settlement_pdd']    = 0;
        $list['settlement_suning'] = 0;
        $list['settlement_vph']    = 0;
        $list['settlement_qita']   = 0;
        $orderCommissionDb         = new OrderCommissions();
        $result                    = $orderCommissionDb->order_count_settlement();
        if (!empty($result)) {
            foreach ($result as $val) {
                switch ($val['order_channel']) {
                    case 'haodanku':
                        $list['settlement_taobao'] = Common::number_randtwo($val['money']);
                        break;
                    case 'elm':
                        $list['settlement_taobao'] += Common::number_randtwo($val['money']);
                        break;
                    case 'jd':
                        $list['settlement_jd'] = Common::number_randtwo($val['money']);
                        break;
                    case 'pdd':
                        $list['settlement_pdd'] = Common::number_randtwo($val['money']);
                        break;
                    case 'suning':
                        $list['settlement_suning'] = Common::number_randtwo($val['money']);
                        break;
                    case 'vph':
                        $list['settlement_vph'] = Common::number_randtwo($val['money']);
                        break;
                    default:
                        $list['settlement_qita'] = Common::number_randtwo($val['money']);
                }
            }
        }

        $list['settlement_total'] = $list['settlement_taobao'] + $list['settlement_jd'] + $list['settlement_pdd'] + $list['settlement_suning'] + $list['settlement_vph'] + $list['settlement_qita'];

        $f_settlement       = new FSettlement();
        $month              = date('Ym', strtotime($date));
        $info               = $f_settlement->getInfo($month);
        $list['set_status'] = $info->status;
        $this->ok($list);
    }

    /**
     * 结算佣金
     */
    public function settleCommissionAction()
    {
        //先核账
        if (!isset($this->params['user_id']) || empty($this->params['user_id'])) {
            $this->fail(-1, '缺少用户user_id');
        }
        if (!isset($this->params['data']) || empty($this->params['data'])) {
            $this->fail(-1, '缺少data');
        }


        $month        = date('Ym', strtotime($this->params['data']));
        $f_settlement = new FSettlement();
        $info         = $f_settlement->getInfo($month);
        if ($info->status == 0) {
            $info->status = 1;
//            $start_end_time['start_at'] = $this->params['data'] . '-01 00:00:00';
//            $start_end_time['end_at']   = date('Y-m-01 00:00:00', strtotime($this->params['data']) + 32 * 86400);
//            $start_end_time['user_id']  = $this->params['user_id'];
            $OrderCommissions          = new OrderCommissions();
            $start_end_time['data'][0] = $this->params['data'] . '-01 00:00:00';
            $start_end_time['data'][1] = $this->params['data'] . '-32 00:00:00';

            $uid = $OrderCommissions->order_user_list($start_end_time);
            if (!empty($uid)) {
                $this->dbMaster->begin();
                $date = date('Ym', strtotime($this->params['data'] . '-01 00:00:00'));
                foreach ($uid as $val) {
                    $fuserSet          = new FUserSettlement();
                    $fuserSet->user_id = $val['user_id'];
                    $fuserSet->month   = $date;
                    if (!$fuserSet->save()) {
                        $this->dbMaster->rollback();
                        $this->fail('添加失败!');
                    }
                }
                $this->dbMaster->commit();

            }
            $info->save();
        }
        $this->ok($info->status);

    }

    /**
     * 金币明细列表
     */
    public function goldListAction()
    {
        if(!isset($this->params['class'])){
            $this->params['class'] = 1;
        }
        $f_user_gold_coin_new_log = new FUserGoldCoinNewLog();
        switch ($this->params['class']) {
            case 1://获得
                $this->params['type'] = '1,2,3,5,6';
                $this->params['status'] = '1';
                $list = $f_user_gold_coin_new_log->page_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '获得金币';
                    }
                }
                break;
            case 2://冻结
                $this->params['status'] = '0';
                $f_user_gold_coin_new_log = new FUserGoldCoinFrozen();
                $list = $f_user_gold_coin_new_log->get_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '冻结金币';
                    }
                }
                break;
            case 3://失效金币
                $this->params['status'] = '2';
                $f_user_gold_coin_new_log = new FUserGoldCoinFrozen();
                $list = $f_user_gold_coin_new_log->get_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '失效金币';
                    }
                }
                break;
            case 4://提现
                $f_wallet_gold_log = new FWalletGoldLog();
                $list = $f_wallet_gold_log->get_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '提现金币';
                    }
                }
                break;
            case 5://清空
                $this->params['type'] = '7';
                $list = $f_user_gold_coin_new_log->page_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '清空金币';
                    }
                }
                break;
            case 6://清空冻结
                $this->params['type'] = '8';
                $list = $f_user_gold_coin_new_log->page_list($this->params);
                if(!empty($list['list'])){
                    foreach ($list['list'] as $key => $val){
                        $list['list'][$key]['class_name'] = '清空冻结金币';
                    }
                }
                break;
        }
        if (!empty($list['list'])) {
            $user = new User();
            foreach ($list['list'] as &$val) {
                $info            = $user->findFirstById($val['user_id']);
                $val['avatar']   = '';
                $val['phone']    = '';
                $val['nickname'] = '';
                if ($info) {
                    $val['avatar']   = $info->avatar;
                    $val['phone']    = $info->phone;
                    $val['nickname'] = $info->nickname;
                }
            }
        }
        $this->ok($list);
    }

    /**
     * 冻结列表
     */
    public function frozen_gold_listAction()
    {
        $f_user_gold_coin_new_log = new FUserGoldCoinFrozen();
        $list                     = $f_user_gold_coin_new_log->get_list($this->params);
        if (!empty($list['list'])) {
            $user = new User();

            foreach ($list['list'] as &$val) {
                $info            = $user->findFirstById($val['user_id']);
                $val['avatar']   = '';
                $val['phone']    = '';
                $val['nickname'] = '';
                if ($info) {
                    $val['avatar']   = $info->avatar;
                    $val['nickname'] = $info->nickname;
                    $val['phone']    = $info->phone;
                }
                $val['due_date'] = '';
                if ($val['type'] == 2) {
                    $due_date        = strtotime($val['order_earning_time']) - time();
                    $val['due_date'] = $this->Sec2Time($due_date);
                }
            }
        }
        $this->ok($list);
    }

    public function Sec2Time($time)
    {
        if (is_numeric($time)) {
            $value = array(
                "years"   => 0, "days" => 0, "hours" => 0,
                "minutes" => 0, "seconds" => 0,
            );
            if ($time >= 31556926) {
                $value["years"] = floor($time / 31556926);
                $time           = ($time % 31556926);
            }
            if ($time >= 86400) {
                $value["days"] = floor($time / 86400);
                $time          = ($time % 86400);
            }
            if ($time >= 3600) {
                $value["hours"] = floor($time / 3600);
                $time           = ($time % 3600);
            }
            if ($time >= 60) {
                $value["minutes"] = floor($time / 60);
                $time             = ($time % 60);
            }
            $value["seconds"] = floor($time);
            //return (array) $value;
            $t = $value["years"] . "年" . $value["days"] . "天" . " " . $value["hours"] . "小时" . $value["minutes"] . "分" . $value["seconds"] . "秒";
            Return $t;

        } else {
            return (bool)FALSE;
        }
    }

    /**
     * 金币统计
     */
    public function goldCountAction()
    {
        $frozen             = new FUserGoldCoinFrozen();
        $result['count']    = $frozen->get_count_new_2($this->params);
        $params['start_at'] = date('Y-m-d H:i:s', strtotime('-59 day'));
        $result['today']    = $frozen->get_count_new($params);
        $params['start_at'] = date('Y-m-d H:i:s', strtotime('-53 day'));
        $result['toweek']   = $frozen->get_count_new($params);
        $this->ok($result);
    }
}
